/*
	vfs_size is in KiloBytes
	Valid range for size is 1 to 1024 (inclusive)
	label name should not exceed 30 characters
*/

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include "..//include//createvfs.h"
#include "..//include//n_ary.h"

int createVFS(char label[], long int vfs_size, char filename_g[])
{
	struct Block b;
	struct header headervar;
	struct FD file_desc;
	
	int i;
	long int blk_start_pos;
	// starting position of the blocks
	
	 num_blocks = (vfs_size*1024)/1024;
	 //freelist = (int*) calloc(num_blocks, sizeof(int));
	 num_used_blocks = 0;
	
	if ((strcmp(label,"") == 0) || vfs_size == 0) {
		printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_00);
		return 0;
	}	
	
					
	// Valid range for size is 1 to 1024 (inclusive)
	if ((vfs_size < 0) || (vfs_size > 1024)) {
		printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_04);
		return 0;
	}
	
	// label name should not exceed 30 characters
	if (strlen(label) > 30) {
		printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_05);
		return 0;
	}
	
	// The slash (/) character is not allowed
	for( i = 0 ; i < strlen(label) ; i++){
		if(label[i]=='/') {
			printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_03);
			return 0;
		} 
        }
    
	
	
					

	FILE *fp_cvfs;
	//printf("%s\n",filename_g);
	if (fopen(filename_g, "r")) {
		printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_01);
		return 0;
	}
	
	fp_cvfs = fopen(filename_g, "wb+");
	if (fp_cvfs == NULL) {
		printf("createvfs_FAILURE %s\n",ERR_VFS_CREATE_02);
		return 0;

	}

	strcpy(headervar.fs_label, label);
	headervar.total_desc = TOTAL_DESC;
	headervar.used_desc = 1;
	fwrite(&headervar, sizeof(struct header), 1, fp_cvfs);

	// initializing fd number values
	rewind(fp_cvfs);
	fseek(fp_cvfs, LABEL_SIZE*sizeof(char) + 2*(sizeof(int)), SEEK_SET);
	for ( i = 0 ; i < TOTAL_DESC ; i++ ) {
		fread(&file_desc, sizeof(struct FD), 1, fp_cvfs);
		file_desc.fdnum = i+1;	
		file_desc.blockno = 0;
		strcpy(file_desc.path,"\0");
		strcpy(file_desc.name,"\0");
		strcpy(file_desc.type,"\0");
		file_desc.size = 0;
		fseek(fp_cvfs, LABEL_SIZE*sizeof(char) + 2*(sizeof(int)) + sizeof(struct FD) * i, SEEK_SET);
		fwrite(&file_desc, sizeof(struct FD), 1, fp_cvfs);
	}
		
	fseek(fp_cvfs, sizeof(struct header), SEEK_SET);			
	//blk_start_pos = ftell(fp_cvfs);							
		
	// allocating space for free list
	// number of free list items = number of blocks
	for(i=0;i<1024;i++){
		freelist[i]=0;
	}
	
	fseek(fp_cvfs, sizeof(struct header), SEEK_SET);
	fwrite(&freelist, sizeof(freelist), 1, fp_cvfs);
		
	for ( i = 0 ; i < num_blocks ; i++ )		
	{
		struct Block b = {"\0"};
		fwrite(&b, sizeof(struct Block), 1, fp_cvfs);
	}
		
	
	fclose(fp_cvfs);
	
	
	return 1;
}
